package com.kylin.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.kylin.bean.AccessToken;
import com.kylin.bean.GitHubOAuthInfo;
import com.kylin.utils.RestTemplateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author kylin
 */
@RestController
@RequestMapping("/oauth")
public class OAuthController {

    @Autowired
    RestTemplateUtil restTemplateUtil;

    @Autowired
    private GitHubOAuthInfo gitHubOAuthInfo;

    @GetMapping("/redirect")
    public String redirect(String code){
        String getAccessTokenUrl = "https://github.com/login/oauth/access_token";
        HttpHeaders headers = new HttpHeaders();
        List<MediaType> mediaTypes = new ArrayList<>();
        //请求头accept设置为：application/json
        mediaTypes.add(MediaType.APPLICATION_JSON);
        headers.setAccept(mediaTypes);
        HashMap<String, String> requestBody = new HashMap<>(16);
        requestBody.put("client_id",gitHubOAuthInfo.getClientId());
        requestBody.put("client_secret",gitHubOAuthInfo.getClientSecret());
        requestBody.put("code",code);
        //请求路径，请求头，请求体，请求响应结果类型，路径参数
        ResponseEntity<String> responseEntity = restTemplateUtil.post(getAccessTokenUrl,headers, requestBody,String.class,new HashMap<>(16));
        String accessTokenJson = responseEntity.getBody();
        System.out.println("令牌Json数据："+accessTokenJson);

        ObjectMapper objectMapper = new ObjectMapper();
        //转换带下划线的属性为驼峰属性
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        try {
            AccessToken accessToken = objectMapper.readValue(accessTokenJson, AccessToken.class);
            headers.set("Authorization","token "+accessToken.getAccessToken());
            String getUserInfoUrl = "https://api.github.com/user";
            ResponseEntity<String> response = restTemplateUtil.get(getUserInfoUrl, headers, String.class, new HashMap<>(16));
            return response.getBody();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
